#!/bin/bash

#############################################################################################
# 用途: 部署 Helm 工具脚本
# 作者: 丁辉
# 更新时间: 2024-03-26
#############################################################################################

function Init_env() {
    # 定义颜色
    RED='\033[0;31m'
    NC='\033[0m'
    GREEN='\033[32m'
    YELLOW='\033[33m'

    # 定义时间格式
    TIME="+%Y-%m-%d %H:%M:%S"

    # 定义函数 send_info
    function SEND_INFO() {
        info=$1
        echo -e "${GREEN}$(date "$TIME") INFO: $info${NC}"
    }

    # 定义函数 send_warn
    function SEND_WARN() {
        warn=$1
        echo -e "${YELLOW}$(date "$TIME") WARN: $warn${NC}"
    }

    # 定义函数 send_error
    function SEND_ERROR() {
        error=$1
        echo -e "${RED}$(date "$TIME") ERROR: $error${NC}"
    }

    if [ $(arch) = "x86_64" ] || [ $(arch) = "amd64" ]; then
        ARCH_TYPE=amd64
    elif [ $(arch) = "aarch64" ] || [ $(arch) = "arm64" ]; then
        ARCH_TYPE=arm64
    elif [ $(arch) = "i386" ]; then
        ARCH_TYPE=amd64
    fi
}

function Install_helm() {
  SEND_INFO "正在检查环境"
  if ! which helm > /dev/null 2>&1; then
        SEND_INFO "Helm 开始安装"
        # 获取版本
        HELM_VERSION=`(curl https://mirrors.huaweicloud.com/helm/ | awk -F '"' '{print $2}' | grep -E '[0-9]+' | sort -rV | awk 'NR==1 {print}' | awk -F '/' '{print $1}')`
        HELM_PACKAGE_VERSION=`(curl https://mirrors.huaweicloud.com/helm/$HELM_VERSION/ | awk -F '"' '{print $2}' | grep -E '[0-9]+' | grep $ARCH_TYPE | grep linux | awk 'NR==1 {print}')`
        # 下载 Helm 安装包
        curl -O https://mirrors.huaweicloud.com/helm/$HELM_VERSION/$HELM_PACKAGE_VERSION
        # 开始安装
        tar -zxvf helm-$HELM_VERSION-linux-$ARCH_TYPE.tar.gz > /dev/null 2>&1
        install -o root -g root -m 0755 linux-$ARCH_TYPE/helm /usr/local/bin/
        # 清理安装包
        rm -rf helm-$HELM_VERSION-linux-$ARCH_TYPE.tar.gz linux-$ARCH_TYPE
        if ! which helm > /dev/null 2>&1; then
            SEND_ERROR "Helm 安装失败"
            exit 1
        else
            VERSION=$(helm version | awk -F '"' '{print $2}')
            SEND_INFO "Helm 安装成功, 版本: $VERSION"
        fi
    else
        VERSION=$(helm version | awk -F '"' '{print $2}')
        SEND_INFO "Helm 已存在, 版本: $VERSION"
    fi
}

function All() {
    Init_env
    Install_helm
}

All